﻿using LuaInterface;
using UnityEngine;
using UnityEngine.UI;

namespace Framework.UGUI
{
	public class ButtonWrap : MonoBehaviour
	{
		public static ButtonWrap Get(GameObject go)
		{
			Button button = go.GetComponent<Button>();
			if (button != null)
			{
				return go.OnceAddComponent<ButtonWrap>();
			}
			return null;
		}

		public static ButtonWrap GetWithPath(GameObject go, string path)
		{
			var buttonTransform = go.transform.Find(path);
			if (buttonTransform != null)
			{
				return Get(buttonTransform.gameObject);
			}
			return null;
		}

		private Button _button;
		public Button button
		{
			get
			{
				if (_button == null)
				{
					_button = gameObject.GetComponent<Button>();
				}
				return _button;
			}
		}

		private GeneralCallBackWithParam _callBack;
		public void AddClickListener(LuaFunction luaCallback, LuaTable luaTarget, object param = null)
		{
			GeneralCallBackWithParam.GetOrReuse(ref _callBack, luaCallback, luaTarget, param);
			button.onClick.RemoveListener(OnClick);
			button.onClick.AddListener(OnClick);
		}

		public void RemoveClickListener()
		{
			GeneralCallBackWithParam.RecycleInst(ref _callBack);
			button.onClick.RemoveAllListeners();
		}

		public void Trigger()
		{
			OnClick();
		}

		private void OnClick()
		{
			if (!Application.isMobilePlatform || Input.touchCount <= 1)
			{
				if (_callBack != null)
				{
					GeneralCallBackWithParam.Invoke(ref _callBack);
				}
			}
		}

		void OnDestroy()
		{
			if (_callBack != null)
			{
				GeneralCallBackWithParam.RecycleInst(ref _callBack); 
				UIEventDebugger.LogUIEventError("ButtonWrap", gameObject);
			}
		}
	}
}
